//
//  ICChatBoxViewController.m
//  ICome
//
//  Created by ENN on 16/3/10.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatBoxViewController.h"
#import "ICChatBoxMoreView.h"
#import "ICChatBoxFaceView.h"
#import "ICMessage.h"
#import "ICMediaManager.h"
#import "ICVideoView.h"
#import "ICVideoManager.h"
#import "UIImage+Extension.h"
#import "ICDocumentViewController.h"
#import "ICChatNetworkManager.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface ICChatBoxViewController ()<ICChatBoxDelegate,ICChatBoxMoreViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,ICDocumentDelegate>

@property (nonatomic, assign) CGRect keyboardFrame;

@property (nonatomic, strong) ICGroup *group;
/** chatBar more view */
@property (nonatomic, strong) ICChatBoxMoreView *chatBoxMoreView;
/** emoji face */
@property (nonatomic, strong) ICChatBoxFaceView *chatBoxFaceView;
/** 录音文件名 */
@property (nonatomic, copy) NSString *recordName;
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, weak) ICVideoView *videoView;

@end

@implementation ICChatBoxViewController

-(instancetype)initWithGroup:(ICGroup *)group {
    if(self = [super init]) {
        self.group = group;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MENU_BACKGROUND_COLOR;
    [self.view addSubview:self.chatBox];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
//    [IQKeyboardManager sharedManager].enable = NO;
    [self.chatBox addNotification];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.chatBox removeNotification];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    [IQKeyboardManager sharedManager].enable = YES;
}

#pragma mark - Public Methods

- (BOOL)resignFirstResponder
{
    if (self.chatBox.status == ICChatBoxStatusShowVideo) { // 录制视频状态
        if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
            [UIView animateWithDuration:0.3 animations:^{
                [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight]];
            } completion:^(BOOL finished) {
                [self.videoView removeFromSuperview]; // 移除video视图
                self.chatBox.status = ICChatBoxStatusNothing;//同时改变状态
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[ICVideoManager shareManager] exit];  // 防止内存泄露
                });
            }];
        }
        return [super resignFirstResponder];
    }
    if (self.chatBox.status != ICChatBoxStatusNothing && self.chatBox.status != ICChatBoxStatusShowVoice) {
        [self.chatBox resignFirstResponder];
        if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
            // 状态改变
            self.chatBox.status = ICChatBoxStatusNothing;
            [UIView animateWithDuration:0.3 animations:^{
                [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight]];
            } completion:^(BOOL finished) {
                [self.chatBoxFaceView removeFromSuperview];
                [self.chatBoxMoreView removeFromSuperview];
            }];
        }
    }
    [self.chatBox setTextViewSizeToFit:YES];

    return [super resignFirstResponder];
}

- (BOOL)becomeFirstResponder
{
    return [super becomeFirstResponder];
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
    if ([eventName isEqualToString:GXRouterEventVideoRecordExit]) {
        [self resignFirstResponder];
    } else if ([eventName isEqualToString:GXRouterEventVideoRecordFinish]) {
        NSString *videoPath = userInfo[VideoPathKey];
        [self resignFirstResponder];
        if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:sendVideoMessage:)]) {
            [_delegate chatBoxViewController:self sendVideoMessage:videoPath];
        }
    } else if ([eventName isEqualToString:GXRouterEventVideoRecordCancel]) {
        NSLog(@"record cancel");
    }else if([eventName isEqualToString:GXRouterEventNoticeMy])
    {
        NSLog(@"@了我");
        if (_delegate && [_delegate respondsToSelector:@selector(noticewho)]) {
            [_delegate noticewho];
        }
    }
}


#pragma mark - Private Methods

- (NSString *)currentRecordFileName
{
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"%ld",(long)timeInterval];
    return fileName;
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    self.keyboardFrame = CGRectZero;
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
        [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight]];
        _chatBox.status = ICChatBoxStatusNothing;
    }
}

- (void)keyboardFrameWillChange:(NSNotification *)notification
{
    self.keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (_chatBox.status == ICChatBoxStatusShowKeyboard && self.keyboardFrame.size.height <= HEIGHT_CHATBOXVIEW) {
        return;
    }
    else if ((_chatBox.status == ICChatBoxStatusShowFace || _chatBox.status == ICChatBoxStatusShowMore) && self.keyboardFrame.size.height <= HEIGHT_CHATBOXVIEW) {
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
        [_delegate chatBoxViewController:self didChangeChatBoxHeight: self.keyboardFrame.size.height + [ICTools getChatBoxInputHeight]];
        _chatBox.status = ICChatBoxStatusShowKeyboard; // 状态改变
    }
    
    [self.chatBox  setTextViewSizeToFit:NO];
}

// 将要弹出视频视图
- (void)videoViewWillAppear
{
    ICVideoView *videoView = [[ICVideoView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, [ICTools getRecordeVideoViewHeight])];
    [self.view insertSubview:videoView aboveSubview:self.chatBox];
    self.videoView = videoView;
    videoView.hidden = YES;
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didVideoViewAppeared:)]) {
        [_delegate chatBoxViewController:self didVideoViewAppeared:videoView];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Getter and Setter

- (ICChatBox *) chatBox
{
    if (_chatBox == nil) {
        _chatBox = [[ICChatBox alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, [ICTools getChatBoxInputHeight])];
        _chatBox.delegate = self;
        _chatBox.group = self.group;
    }
    return _chatBox;
}

- (ICChatBoxFaceView *)chatBoxFaceView
{
    if (!_chatBoxFaceView) {
        _chatBoxFaceView = [[ICChatBoxFaceView alloc] initWithFrame:CGRectMake(0, [ICTools getChatBoxInputHeight] - [ICTools getHomebarHeight], App_Frame_Width, HEIGHT_CHATBOXVIEW)];
    }
    return _chatBoxFaceView;
}

- (ICChatBoxMoreView *)chatBoxMoreView
{
    if (!_chatBoxMoreView) {
        _chatBoxMoreView = [[ICChatBoxMoreView alloc] initWithFrame:CGRectMake(0, [ICTools getChatBoxInputHeight] - [ICTools getHomebarHeight], App_Frame_Width, HEIGHT_CHATBOXVIEW)];
        _chatBoxMoreView.delegate = self;
        // 创建Item
        ICChatBoxMoreViewItem *photosItem = [ICChatBoxMoreViewItem createChatBoxMoreItemWithTitle:@"图片"
                                                                                        imageName:@"icon_sharemore_pic"];
        ICChatBoxMoreViewItem *takePictureItem = [ICChatBoxMoreViewItem createChatBoxMoreItemWithTitle:@"拍照"
                                                                                             imageName:@"icon_sharemore_video"];
        ICChatBoxMoreViewItem *videoItem = [ICChatBoxMoreViewItem createChatBoxMoreItemWithTitle:@"短视频"
                                                                                       imageName:@"icon_sharemore_sight"];
        ICChatBoxMoreViewItem *docItem = [ICChatBoxMoreViewItem createChatBoxMoreItemWithTitle:@"文件"
                                                                                     imageName:@"icon_sharemore_wallet"];
//        ICChatBoxMoreViewItem * zoomVideo= [ICChatBoxMoreViewItem createChatBoxMoreItemWithTitle:@"视频会议"// videoconferencing
//                                                                                     imageName:@"icon_sharemore_video_meeting"];

        //        ICChatBoxMoreViewItem *redPacketItem = [ICChatBoxMoreViewItem createChatBoxMoreItemWithTitle:@"红包"
        //                                                                                     imageName:@"icon_sharemore_redpacket"];
        //        if ([self.group.gId containsString:@"dbl"] || [self.group.gId containsString:@"mlt"]) {
        //            [_chatBoxMoreView setItems:[[NSMutableArray alloc] initWithObjects:photosItem, takePictureItem, videoItem, docItem, redPacketItem, nil]];
        //        }else {
        [_chatBoxMoreView setItems:[[NSMutableArray alloc] initWithObjects:photosItem, takePictureItem, videoItem, docItem, nil]];
        //        }
    }
    return _chatBoxMoreView;
}

- (UIImagePickerController *)imagePicker
{
    if (nil == _imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.modalPresentationStyle = UIModalPresentationCustom;
        _imagePicker.view.backgroundColor = [UIColor whiteColor];
    }
    return _imagePicker;
}


#pragma mark - ICChatBoxMoreViewDelegate

- (void) chatBoxMoreView:(ICChatBoxMoreView *)chatBoxMoreView
           didSelectItem:(ICChatBoxItem)itemType
{
    __weak typeof(self)weak_self = self;
    if (itemType == ICChatBoxItemAlbum) {       // 相册
        
        [ICSystemTool checkPhotoAuthorizationStatus:^{
            
            [weak_self pushImagePickerController];
        }];
        
    } else if (itemType == ICChatBoxItemCamera){    // camera
        
        [ICSystemTool checkCameraAuthorizationStatus:^{
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                weak_self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [weak_self presentViewController:weak_self.imagePicker animated:YES completion:nil];
            } else {
                NSLog(@"camera is no available!");
            }
        }];
        
    } else if (itemType == ICChatBoxItemVideo) {
        [self resignFirstResponder];
        
        [ICSystemTool checkAudioAuthorizationStatus:^{
            
            [NSTimer scheduledTimerWithTimeInterval:0.3
                                             target:weak_self
                                           selector:@selector(videoViewWillAppear)
                                           userInfo:nil
                                            repeats:NO]; // 待动画完成
        }];
        
    } else if (itemType == ICChatBoxItemDoc) {
        ICDocumentViewController *docVC = [[ICDocumentViewController alloc] init];
        docVC.delegate = self;
        [self.navigationController pushViewController:docVC animated:YES];
    } else if (itemType == ICChatBoxItemRedPacket) {    //redpacket
        NSDictionary *dict = @{@"groupId":self.group.gId};
        if ([self.group.gId containsString:@"dbl"]) { //单人红包
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketSingleViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }else if ([self.group.gId containsString:@"mlt"]) {   //群组红包
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketGroupViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
    }else if (itemType == ICChatBoxItemZoomVideo){//视频会议
        __block NSMutableArray * userarray = [NSMutableArray array];
        
        [ICMessageDatabase getUsersWithGroupId:self.group.gId finish:^(NSArray *array, NSError *error) {
            if (array.count == 0) { // 数据异常
                [ICMessageHelper setGroupInfoLastUpdate:@0 gId:self.group.gId];
            }
            NSLog(@"array = %@",array);
            for(ICUser * user in array)
            {
                if(![user.eId isEqualToString:[ICUser currentUser].eId] && ![user.eId hasPrefix:@"bot"])
                {
                    [userarray addObject:user.eId];
                }
            }
        }];
        
        if ([self.group.gType intValue] == 1 || [self.group.gType intValue] == 2) {
            

        }else{
             [MBProgressHUD showSuccess:@"您无法使用视频会议"];
        }
        
      }
}


-(void)loadbeginDate:(NSString *)vcId
{
    self.videoVcId = vcId;
    
    __weak typeof(self) weakSelf = self;
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:sendZoomvideoMessage:)]) {
        [_delegate chatBoxViewController:weakSelf sendZoomvideoMessage:vcId];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSLog(@"movie");
    } else {
        UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
        [picker dismissViewControllerAnimated:YES completion:nil];
        // 图片压缩后再上传服务器
        // 保存路径
        UIImage *simpleImg = [UIImage simpleImage:orgImage];
        NSString *filePaht = [[ICMediaManager sharedManager] saveImage:simpleImg];
        if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:sendImageMessage:imagePath:)]) {
            [_delegate chatBoxViewController:self sendImageMessage:simpleImg imagePath:filePaht];
        }
    }
}

- (void)pushImagePickerController {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:1 delegate:nil pushPhotoPickerVc:YES];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = YES;
    imagePickerVc.allowCrop = NO;// 裁剪
    imagePickerVc.needCircleCrop = NO;// 圆
    imagePickerVc.circleCropRadius = 100;
    
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (isSelectOriginalPhoto) {
            for (UIImage *image in photos) {
                [[TZImageManager manager] getOriginalPhotoWithAsset:image newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                    [self sendImage:photo];
                }];
            }
        } else {
            for (UIImage *image in photos) {
                [self sendImage:image];
            }
        }
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)sendImage:(UIImage *)image {
    UIImage *simpleImg = [UIImage simpleImage:image];
    NSString *filePaht = [[ICMediaManager sharedManager] saveImage:simpleImg];
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:sendImageMessage:imagePath:)]) {
        [_delegate chatBoxViewController:self sendImageMessage:simpleImg imagePath:filePaht];
    }
}

#pragma mark - ICChatBoxDelegate

/**
 *  输入框状态改变
 *
 *  @param chatBox    chatBox
 *  @param fromStatus 起始状态
 *  @param toStatus   目的状态
 */
- (void)chatBox:(ICChatBox *)chatBox changeStatusForm:(ICChatBoxStatus)fromStatus to:(ICChatBoxStatus)toStatus
{
    if (toStatus == ICChatBoxStatusShowKeyboard) {  // 显示键盘
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.chatBoxFaceView removeFromSuperview];
            [self.chatBoxMoreView removeFromSuperview];
        });
    } else if (toStatus == ICChatBoxStatusShowVoice) {    // 语音输入按钮
        [UIView animateWithDuration:0.3 animations:^{
            if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
                [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight]];
            }
        } completion:^(BOOL finished) {
            [self.chatBoxFaceView removeFromSuperview];
            [self.chatBoxMoreView removeFromSuperview];
        }];
    } else if (toStatus == ICChatBoxStatusShowFace) {     // 表情面板
        if (fromStatus == ICChatBoxStatusShowVoice || fromStatus == ICChatBoxStatusNothing) {
            self.chatBoxFaceView.y = [ICTools getChatBoxInputHeight] - [ICTools getHomebarHeight];
            [self.view addSubview:self.chatBoxFaceView];
            [UIView animateWithDuration:0.3 animations:^{
                if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
                    [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight] + HEIGHT_CHATBOXVIEW];
                }
            }];
        } else {  // 表情高度变化
            self.chatBoxFaceView.y = [ICTools getChatBoxInputHeight] + HEIGHT_CHATBOXVIEW;
            [self.view addSubview:self.chatBoxFaceView];
            [UIView animateWithDuration:0.3 animations:^{
                self.chatBoxFaceView.y = [ICTools getChatBoxInputHeight] - [ICTools getHomebarHeight];
            } completion:^(BOOL finished) {
                [self.chatBoxMoreView removeFromSuperview];
            }];
            if (fromStatus != ICChatBoxStatusShowMore) {
                [UIView animateWithDuration:0.2 animations:^{
                    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
                        [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight] + HEIGHT_CHATBOXVIEW];
                    }
                }];
            }
        }
    } else if (toStatus == ICChatBoxStatusShowMore) {
        if (fromStatus == ICChatBoxStatusShowVoice || fromStatus == ICChatBoxStatusNothing) {
            self.chatBoxMoreView.y = [ICTools getChatBoxInputHeight] - [ICTools getHomebarHeight];
            [self.view addSubview:self.chatBoxMoreView];
            [UIView animateWithDuration:0.3 animations:^{
                if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
                    [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight] + HEIGHT_CHATBOXVIEW];
                }
            }];
        } else {
            self.chatBoxMoreView.y = [ICTools getChatBoxInputHeight] + HEIGHT_CHATBOXVIEW;
            [self.view addSubview:self.chatBoxMoreView];
            [UIView animateWithDuration:0.3 animations:^{
                self.chatBoxMoreView.y = [ICTools getChatBoxInputHeight]- [ICTools getHomebarHeight];
            } completion:^(BOOL finished) {
                [self.chatBoxFaceView removeFromSuperview];
            }];
            
            [UIView animateWithDuration:0.2 animations:^{
                if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
                    [_delegate chatBoxViewController:self didChangeChatBoxHeight:[ICTools getChatBoxInputHeight] + HEIGHT_CHATBOXVIEW];
                }
            }];
        }
    } else if (toStatus == ICChatBoxStatusNothing) {
        if ([_delegate respondsToSelector:@selector(chatBoxViewController:showPubMenu:)]) {
            [_delegate chatBoxViewController:self showPubMenu:YES];
        }
        [self resignFirstResponder];
    }
    
}


- (void)chatBox:(ICChatBox *)chatBox sendTextMessage:(NSString *)textMessage
{
    NSLog(@"chatBox: sendTextMessage:");
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:sendTextMessage:)]) {
        [_delegate chatBoxViewController:self sendTextMessage:textMessage];
    }
}

/**
 *  输入框高度改变
 *
 *  @param chatBox chatBox
 *  @param height  height
 */
- (void)chatBox:(ICChatBox *)chatBox changeChatBoxHeight:(CGFloat)height
{
    self.chatBoxFaceView.y = height - [ICTools getHomebarHeight];
    self.chatBoxMoreView.y = height - [ICTools getHomebarHeight];
    self.chatBox.height = height;
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:didChangeChatBoxHeight:)]) {
        float h = 0;
        if (self.chatBox.status == ICChatBoxStatusShowFace) {
            h  =  HEIGHT_CHATBOXVIEW + height ;
        } else if (self.chatBox.status == ICChatBoxStatusShowMore) {
            h  =  HEIGHT_MOREVIEW  + height ;
        } else if (self.chatBox.status == ICChatBoxStatusNothing) {
            h = self.keyboardFrame.size.height + height;
        } else {
            h = self.keyboardFrame.size.height + height - [ICTools getHomebarHeight];
        }
        [_delegate chatBoxViewController:self didChangeChatBoxHeight: h];
    }
}

- (void)chatBoxDidStartRecordingVoice:(ICChatBox *)chatBox
{
    if ([_delegate respondsToSelector:@selector(chatBoxProcessingBeforeStartRecordingVoice)]) {
        [_delegate chatBoxProcessingBeforeStartRecordingVoice];
    }
    self.recordName = [self currentRecordFileName];
    [[ICRecordManager shareManager] startRecordingWithFileName:self.recordName completion:^(NSError *error) {
        if (error) {   // 加了录音权限的判断
        } else {
            if ([_delegate respondsToSelector:@selector(voiceDidStartRecording)]) {
                [_delegate voiceDidStartRecording];
            }
        }
    }];
}

- (void)chatBoxDidStopRecordingVoice:(ICChatBox *)chatBox
{
    __weak typeof(self) weakSelf = self;
    [[ICRecordManager shareManager] stopRecordingWithCompletion:^(NSString *recordPath) {
        if ([recordPath isEqualToString:shortRecord]) {
            if ([_delegate respondsToSelector:@selector(voiceRecordSoShort)]) {
                [_delegate voiceRecordSoShort];//shortRecord 时间短
            }
            [[ICRecordManager shareManager] removeCurrentRecordFile:weakSelf.recordName];
        } else {    // send voice message
            if (_delegate && [_delegate respondsToSelector:@selector(chatBoxViewController:sendVoiceMessage:)]) {
                [_delegate chatBoxViewController:weakSelf sendVoiceMessage:recordPath];
            }
        }
    }];
}
- (void)chatBoxDidCancelRecordingVoice:(ICChatBox *)chatBox
{
    if ([_delegate respondsToSelector:@selector(voiceDidCancelRecording)]) {
        [_delegate voiceDidCancelRecording];
    }
    [[ICRecordManager shareManager] removeCurrentRecordFile:self.recordName];
}

- (void)chatBoxDidDrag:(BOOL)inside
{
    if ([_delegate respondsToSelector:@selector(voiceWillDragout:)]) {
        [_delegate voiceWillDragout:inside];
    }
}


#pragma mark - ICDocumentDelegate

- (void)selectedFileName:(NSString *)fileName
{
    if ([self.delegate respondsToSelector:@selector(chatBoxViewController:sendFileMessage:)]) {
        [self.delegate chatBoxViewController:self sendFileMessage:fileName];
    }
}

#pragma mark - H.323/SIP call state changed

#if 0
- (void)onSendPairingCodeStateChanged:(NSUInteger)state
{
    NSLog(@"onSendPairingCodeStateChanged %zd", state);
}

- (void)onCallRoomDeviceStateChanged:(NSUInteger)state
{
    NSLog(@"onCallRoomDeviceStateChanged %zd", state);
}
#endif


@end
